package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppOrderDetailMapper;
import com.eco.fanliapp.dao.AppUserMapper;
import com.eco.fanliapp.dao.AppUserOrderMapper;
import com.eco.fanliapp.dao.AppUserRewardSetupMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

/**
 * 订单 服务层实现
 *
 * @author xiaoxx
 * @date 2019-04-24
 */
@Service
public class AppOrderDetailServiceImpl extends ServiceImpl<AppOrderDetailMapper, AppOrderDetail> implements IAppOrderDetailService {
    private static final Logger log = LoggerFactory.getLogger(AppOrderDetailServiceImpl.class);

    @Autowired
    private AppOrderDetailMapper appOrderDetailMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private AppUserOrderMapper appUserOrderMapper;

    @Autowired
    private IUserCashschemeService userCashschemeService;

    @Autowired
    private IAppCompanyService appCompanyService;

    @Autowired
    private IAppUserRedRewardService iAppUserRedRewardService;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private ISyUserTaskService iSyUserTaskService;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private ISyTaskTypeService iSyTaskTypeService;
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private SysLogCommon sysLogCommon;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private IAppUserOrderService appUserOrderService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private AppUserRewardSetupMapper appUserRewardSetupMapper;
    @Autowired
    private IAppUserRedRewardService appUserRedRewardService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private ISySwitchService iSySwitchService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;
    @Autowired
    private IAppOrderDetailService appOrderDetailService;

    /**
     * 查询订单信息
     *
     * @param orderDetailid 订单ID
     * @return 订单信息
     */
    @Override
    public AppOrderDetail selectAppOrderDetailById(String orderDetailid) {
        return appOrderDetailMapper.selectAppOrderDetailById(orderDetailid);
    }

    /**
     * 查询订单列表
     *
     * @param appOrderDetail 订单信息
     * @return 订单集合
     */
    @Override
    public List<AppOrderDetail> selectAppOrderDetailList(AppOrderDetail appOrderDetail) {
        return appOrderDetailMapper.selectAppOrderDetailList(appOrderDetail);
    }

    /**
     * 新增订单
     *
     * @param appOrderDetail 订单信息
     * @return 结果
     */
    @Override
    public int insertAppOrderDetail(AppOrderDetail appOrderDetail) {
        return appOrderDetailMapper.insertAppOrderDetail(appOrderDetail);
    }

    /**
     * 修改订单
     *
     * @param appOrderDetail 订单信息
     * @return 结果
     */
    @Override
    public int updateAppOrderDetail(AppOrderDetail appOrderDetail) {
        return appOrderDetailMapper.updateAppOrderDetail(appOrderDetail);
    }

    /**
     * 删除订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAppOrderDetailByIds(String ids) {
        return appOrderDetailMapper.deleteAppOrderDetailByIds(Convert.toStrArray(ids));
    }

    @Override
    public List<AppOrderDetailVo> selectAppOrderDetailTkStatus3(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetailTkStatus3(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetailVo> selectAppOrderDetailTkStatus13(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetailTkStatus13(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetailVo> selectAppOrderDetailTkStatusNot3And13(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetailTkStatusNot3And13(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetailVo> selectAppOrderDetailTkStatusAll(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetailTkStatusAll(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetailVo> selectJdOrderDetailTkStatus(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectJdOrderDetailTkStatus(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetailVo> selectPddOrderDetailTkStatus(Long userId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectPddOrderDetailTkStatus(userId, tkStatus, pageNum, pageSize);
    }

    @Override
    public List<AppOrderDetail> selectOrderDetailItemISnull() {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectOrderDetailItemISnull();
    }

    @Override
    public List<AppOrderDetail> selectAppOrderDetailBytradeId(Long userId, Long orderId) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetailBytradeId(userId, orderId);
    }

    private List<OrderDetailInfo> getOrderDetailInfo(List<AppOrderDetail> appOrderDetails) {
        ArrayList<OrderDetailInfo> orderDetailInfos = new ArrayList<>();
        // 查询用户的详情
        for (AppOrderDetail orderDetail : appOrderDetails) {
            OrderDetailInfo orderDetailInfo = new OrderDetailInfo();
            orderDetailInfo.setOrderDetail(orderDetail);
            Long taobaoUserId = orderDetail.getTaobaoUserId();
            AppUser appUser = appUserMapper.selectAppUserListByTaoBaoUserId(taobaoUserId);
            if (!StringUtils.isEmpty(appUser)) {
                orderDetailInfo.setUserName(appUser.getWechatNickname());
                orderDetailInfo.setWechatUnionid(appUser.getWechatUnionid());
            }
            // 设置直接粉丝佣金
            orderDetailInfo.setPrimaryFansCommission(2.00);
            // 设置间接粉丝佣金
            orderDetailInfo.setSecondaryFansCommission(2.00);
            // 设置客户比列
            orderDetailInfo.setCustomerRate(5.0);
            // 设置客户佣金
            orderDetailInfo.setCustomerCommission(1.1);
            orderDetailInfos.add(orderDetailInfo);
        }
        return orderDetailInfos;
    }

    /**
     * 查询订单列表
     *
     * @param
     * @return
     */
    @Override
    public ServerResponse<PageInfo> selectAppOrderDetailList(Integer currentPage, Integer pageSize, Integer companyId, String goodsPlatform, String payStatus, String startTime, String endTime, String keyWord
    ) {
        Long longStartTime = null;
        Long longEndTime = null;
        try {
            if (!StringUtils.isEmpty(startTime)) {
                longStartTime = DateFormatUtils.stringToLong(startTime, "yyyy-MM-dd HH:mm:ss");
            }
            if (!StringUtils.isEmpty(endTime)) {
                longEndTime = DateFormatUtils.stringToLong(endTime, "yyyy-MM-dd HH:mm:ss");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("goodsPlatform", goodsPlatform);
        hashMap.put("payStatus", payStatus);
        hashMap.put("startTime", longStartTime);
        hashMap.put("endTime", longEndTime);
        hashMap.put("keyWord", keyWord);
        hashMap.put("companyId", companyId);
        AppCompany appCompany = appCompanyService.selectAppCompanyById(companyId);
        if (appCompany.getType() == 1) {
            hashMap.put("companyId", -1);
        }
        PageHelper.startPage(currentPage, pageSize);
        List<HashMap<String, Object>> list = appOrderDetailMapper.findAppOrderDetail(hashMap);
        for (HashMap map : list) {
            MapValueHelper mapValueHelper = new MapValueHelper(map);
            List<AppUserOrder> userOrderList = appUserOrderMapper.selectAppUserOrderListByTradeId(mapValueHelper.getLong("trade_id"));
            // map.put("userOrderList", userOrderList);
            String pubSharePreFee = mapValueHelper.getString("pub_share_pre_fee");//联盟佣金
            BigDecimal money = new BigDecimal(pubSharePreFee);
            BigDecimal sum = new BigDecimal("0");
            if (userOrderList.size() > 0) {
                for (AppUserOrder appUserOrder : userOrderList) {
                    sum = sum.add(appUserOrder.getCommission());
                    if (appUserOrder.getOrderGrade() == 1) {
                        map.put("meCommission", appUserOrder.getCommission());
                    } else if (appUserOrder.getOrderGrade() == 2) {
                        map.put("subCommission", appUserOrder.getCommission());
                    } else {
                        map.put("subCommission", "");
                    }
                }
                map.put("sum", money.subtract(sum));

            } else {
                map.put("sum", money);
            }


            long user_id = mapValueHelper.getLong("user_id");
			/*Integer kehuRatios = userCashschemeService.getCommissionRate(user_id, Double.valueOf(pubSharePreFee));
			map.put("kehu_ratios",kehuRatios);*/
        }
        return ServerResponse.createBySuccess("查找成功", new PageInfo(list));
    }


    @Override
    public ServerResponse<PageInfo> selectAppOrderDetailByKeyWord(String goodsPlatform, String payStatus, String startTime, String endTime, String keyWord, int currentPage, int pageSize, Integer companyId) {

        Long longStartTime = null;
        Long longEndTime = null;
        try {
            if (!StringUtils.isEmpty(startTime)) {
                longStartTime = DateFormatUtils.stringToLong(startTime, "yyyy-MM-dd HH:mm:ss");
            }
            if (!StringUtils.isEmpty(endTime)) {
                longEndTime = DateFormatUtils.stringToLong(endTime, "yyyy-MM-dd HH:mm:ss");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (StringUtils.isEmpty(payStatus)) {
            payStatus = "0";
        }
        AppCompany appCompany = appCompanyService.selectAppCompanyById(companyId);
        if (appCompany.getType() == 1) {
            companyId = -1;
        }

        if ("0".equalsIgnoreCase(payStatus)) {
            PageHelper.startPage(currentPage, pageSize);
            List<AppOrderDetail> appOrderDetails = appOrderDetailMapper.selectAppOrderDetailByKeyWordWithoutPayStatus(goodsPlatform, longStartTime, longEndTime, keyWord, companyId);
            if (appOrderDetails == null) {
                return ServerResponse.createByErrorMessage("查询失败");
            }
            List<OrderDetailInfo> orderDetailInfos = getOrderDetailInfo(appOrderDetails);
            return ServerResponse.createBySuccess("查询成功", new PageInfo(orderDetailInfos));
        }
        PageHelper.startPage(currentPage, pageSize);
        List<AppOrderDetail> appOrderDetails = appOrderDetailMapper.selectAppOrderDetailByKeyWord(goodsPlatform, payStatus, longStartTime, longEndTime, keyWord, companyId);
        if (!CollectionUtils.isEmpty(appOrderDetails)) {
            return ServerResponse.createByErrorMessage("查询失败");
        }
        List<OrderDetailInfo> orderDetailInfos = getOrderDetailInfo(appOrderDetails);
        return ServerResponse.createBySuccess("查询成功", new PageInfo(orderDetailInfos));
    }

    /**
     * 查询我的团队下级订单
     *
     * @param relationId
     * @param specialId
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<AppOrderDetail> findTeamLevalOrderList(Long relationId, Long specialId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.findTeamLevalOrderLists(relationId, specialId, tkStatus, pageNum, pageSize);
    }

    /**
     * 查询我的团队下下级订单
     *
     * @param relationId
     * @param specialId
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<AppOrderDetail> findTeamLeval2OrderList(Long relationId, Long specialId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.findTeamLeval2OrderLists(relationId, specialId, tkStatus, pageNum, pageSize);
    }

    @Override
    public int deleteAppOrderDetailById(String orderDetailid) {
        return appOrderDetailMapper.deleteAppOrderDetailById(orderDetailid);
    }

    @Override
    public List<AppOrderDetail> selectAppOrderDetail(AppOrderDetail detail) {
        // TODO Auto-generated method stub
        return appOrderDetailMapper.selectAppOrderDetail(detail);
    }

    @Override
    public List<AppOrderDetail> selectAppOrderDetailFailList() {
        // TODO Auto-generated method selectAppOrderDetailFailList 查询所有非失效订单
        return appOrderDetailMapper.selectAppOrderDetailFailList();
    }

    /**
     * 根据trade查询订单信息
     *
     * @param tradeId 订单ID
     * @return 订单信息
     */
    @Override
    public AppOrderDetail selectAppOrderDetailByTradeId(Long tradeId) {
        return appOrderDetailMapper.selectAppOrderDetailByTradeId(tradeId);
    }

    @Override
    public int selectOrderIsTodayCount(long startTodayTime, long endTodayTime, Long userId) {
        return appOrderDetailMapper.selectOrderIsTodayCount(startTodayTime, endTodayTime, userId);
    }

    /**
     * 根据unionId查询订单数量
     *
     * @param taobaoUserId
     * @return 订单总数量
     */
    @Override
    public int selectAppUserOrderCount(Long taobaoUserId) {
        return appOrderDetailMapper.selectAppUserOrderCount(taobaoUserId);
    }

    /**
     * 设置维权订单
     *
     * @param tradeId
     * @return
     */
    @Override
    public ServerResponse violationsToSet(Long tradeId, UserVO authentication) {
        List<AppUserOrder> list = appUserOrderMapper.selectAppUserOrderListByTradeId(tradeId);
        Administrator administrator = administratorService.getById(authentication.getUserId());
        if (list != null && list.size() > 0) {
            for (AppUserOrder appUserOrder : list) {
                SysLog sysLog = new SysLog();
                sysLog.setUserId(authentication.getUserId());
                sysLog.setMethodExplain(administrator.getAdminitratorName() + "把订单号为" + appUserOrder.getOrderId() + "设置成违规订单");
                if (appUserOrder != null && appUserOrder.getOrderSettleStatus() == 3) {
                    sysLog.setResponseParams("设置失败,已经是违规订单");
                    return ServerResponse.createByErrorCodeMessage(702, "设置失败,已经是违规订单");
                }

                if (appUserOrder != null && appUserOrder.getOrderSettleStatus() == 1) {
                    AppUserOrder order = new AppUserOrder();
                    order.setTableId(appUserOrder.getTableId());
                    order.setOrderStatus(13);//设置为失效
                    order.setOrderSettleStatus(3);//违规订单
                    int i = appUserOrderMapper.updateAppUserOrder(order);

                    if (i > 0) {
                        sysLog.setResponseParams("未结算订单，违规订单设置成功");
                        log.info("未结算订单，违规订单设置成功，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                    } else {
                        sysLog.setResponseParams("未结算违规订单修改状态失败");
                        log.error("未结算违规订单修改状态失败，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                    }
                    AppUserRedReward appUserRedReward = iAppUserRedRewardService.selectAppUserRedRewardById(appUserOrder.getOrderId(), appUserOrder.getUserId());
                    if (appUserRedReward != null && appUserRedReward.getHbStatus() != 5) {
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);
                        if (appUserRedReward.getHbType() == 3) {
                            log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            updateUserCommon.UpdateUserTaskStatus(appUserOrder.getUserId(), 6);
                        }
                    }

                } else if (appUserOrder != null && appUserOrder.getOrderSettleStatus() == 2) {
                    AppUserOrder order = new AppUserOrder();
                    order.setTableId(appUserOrder.getTableId());
                    order.setOrderStatus(13);//设置为失效
                    order.setOrderSettleStatus(3);//违规订单
                    int i = appUserOrderMapper.updateAppUserOrder(order);
                    if (i > 0) {
                        sysLog.setResponseParams("结算订单，违规订单设置成功");
                        log.info("结算订单，违规订单设置成功，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                        AppUser appUser = appUserMapper.selectAppUserByUserId(appUserOrder.getUserId());
                        BigDecimal balance = appUser.getBalance();
                        AppUser appUser1 = new AppUser();
                        appUser1.setTableId(appUser.getTableId());
                        appUser1.setUserId(appUser.getUserId());
                        appUser1.setBalance(balance.subtract(appUserOrder.getCommission()));
                        int ii = appUserMapper.updateAppUser(appUser1);
                        log.info("分佣扣除成功，userId{}用户余额{}", appUserOrder.getUserId(), balance.subtract(appUserOrder.getCommission()).toString());

                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(appUserOrder.getUserId(), balance, BigDecimalUtils.Format(appUserOrder.getCommission()), "违规订单分佣扣除", 2, 1);

                    } else {
                        log.info("分佣扣除失败，userId{}", appUserOrder.getUserId());

                    }

                    AppUserRedReward appUserRedReward = iAppUserRedRewardService.selectAppUserRedRewardById(appUserOrder.getOrderId(), appUserOrder.getUserId());

                    if (appUserRedReward != null && appUserRedReward.getHbStatus() == 5) {
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);

                        if (appUserRedReward.getHbType() == 3) {
                            if (j) {
                                log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            } else {
                                log.error("首购红包设置失效失败，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            }
                            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(2);
                            SyUserTask syUserTask = new SyUserTask();
                            syUserTask.setUserId(appUserRedReward.getUserId());
                            syUserTask.setTaskTypeId(2);
                            syUserTask.setTaskType(syTaskType.getTaskType());
                            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
                            syUserTask.setTaskStatus(5);
                            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
                            syUserTask.setTaskRewardMoney(BigDecimal.valueOf(0).subtract(syTaskType.getTaskRewardMoney()));
                            syUserTask.setTaskRewardDate(new Date());
                            syUserTask.setEnable(1);
                            iSyUserTaskService.insertsyUserTask(syUserTask);
                        } else if (appUserRedReward.getHbType() == 2) {
                            if (j) {
                                log.info("邀请红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            } else {
                                log.error("邀请红包设置失效失败");
                            }
                            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(5);
                            SyUserTask syUserTask = new SyUserTask();
                            syUserTask.setUserId(appUserRedReward.getUserId());
                            syUserTask.setTaskTypeId(5);
                            syUserTask.setTaskType(syTaskType.getTaskType());
                            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
                            syUserTask.setTaskStatus(5);
                            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
                            syUserTask.setTaskRewardMoney(BigDecimal.valueOf(0).subtract(syTaskType.getTaskRewardMoney()));
                            syUserTask.setTaskRewardDate(new Date());
                            syUserTask.setEnable(1);
                            iSyUserTaskService.insertsyUserTask(syUserTask);
                        }

                        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(appUserOrder.getUserId());
                        if (syUserMoney != null) {
                            SyUserMoney syUserMoney1 = new SyUserMoney();
                            syUserMoney1.setTableId(syUserMoney.getTableId());
                            syUserMoney1.setCashBalanceAmount(syUserMoney.getCashBalanceAmount().subtract(appUserRedReward.getHbMoney()));
                            syUserMoney1.setCashTotalAmount(syUserMoney.getCashTotalAmount().subtract(appUserRedReward.getHbMoney()));
                            int jj = iSyUserMoneyService.updateSyUserMoney(syUserMoney1);
                            if (jj > 0) {
                                log.info("微信余额扣除红包奖励成功，userId{}金额{}余额{}", syUserMoney.getUserId(), appUserRedReward.getHbMoney(), syUserMoney.getCashBalanceAmount().subtract(appUserRedReward.getHbMoney()));
                            } else {
                                log.error("红包奖励扣除失败，userId{}金额{}", syUserMoney.getUserId(), appUserRedReward.getHbMoney());
                            }
                        }
                    } else if (appUserRedReward != null && (appUserRedReward.getHbStatus() == 2 || appUserRedReward.getHbStatus() == 3)) {
                        //红包未到账时,设置红包失效
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);

                        if (appUserRedReward.getHbType() == 3) {
                            log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            updateUserCommon.UpdateUserTaskStatus(appUserOrder.getUserId(), 6);
                        }
                    }

                }
                sysLogCommon.save(sysLog);
            }
            return ServerResponse.createBySuccessMessage("设置成功");
        }
        return ServerResponse.createByErrorCodeMessage(701, "订单不存在");
    }

    @Override
    public int totalGoodFrees(Integer companyId, Integer flag, long startTime, long endTime) {
        return appOrderDetailMapper.totalGoodFrees(companyId, flag, startTime, endTime);
    }

    @Override
    public int yesterdayTotalGoodFrees() {
        return appOrderDetailMapper.yesterdayTotalGoodFrees();
    }

    @Override
    public ServerResponse<PageInfo> selectAppOrderDetailListNew(Integer currentPage, Integer pageSize, Integer companyId, String goodsPlatform, String payStatus, String startTime, String endTime, String keyWord, Integer deleted) {
        Long longStartTime = null;
        Long longEndTime = null;
        try {
            if (!StringUtils.isEmpty(startTime)) {
                longStartTime = DateFormatUtils.stringToLong(startTime, DateFormatUtils.STANDARD_FORMAT);
            }
            if (!StringUtils.isEmpty(endTime)) {
                longEndTime = DateFormatUtils.stringToLong(endTime, DateFormatUtils.STANDARD_FORMAT);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        HashMap<String, Object> hashMap = new HashMap<String, Object>();
//        hashMap.put("goodsPlatform", goodsPlatform);
        hashMap.put("payStatus", payStatus);
        hashMap.put("startTime", longStartTime);
        hashMap.put("endTime", longEndTime);
        hashMap.put("keyWord", keyWord);
        hashMap.put("companyId", companyId);
        hashMap.put("deleted", deleted);
        PageHelper.startPage(currentPage, pageSize);
        List<AppOrderDetailVo> list = new ArrayList<>();
        if ("1".equals(goodsPlatform) || StringUtils.isEmpty(goodsPlatform)) {
            //淘宝
            list = appOrderDetailMapper.findAppOrderDetailNew(hashMap);
        } else if ("2".equals(goodsPlatform)) {
            //京东
            list = appOrderDetailMapper.findJdAppOrderDetailNew(hashMap);

        } else if ("3".equals(goodsPlatform)) {
            //拼多多
            list = appOrderDetailMapper.findPddAppOrderDetailNew(hashMap);
        }
        return ServerResponse.createBySuccess("查找成功", new PageInfo(list));
    }

    @Override
    public List<AppOrderDetail> orderCheckList() {
        return appOrderDetailMapper.orderCheckList();
    }

    @Override
    public List<AppOrderDetail> orderCheckUserOrderList() {
        return appOrderDetailMapper.orderCheckUserOrderList();
    }


    @Override
    public List<OrderIdVo> violationsToSetList(HttpServletResponse response, MultipartFile file, UserVO authentication) {
        List<OrderIdVo> listResult = new ArrayList<>();
        try {
            List<OrderIdVo> list = EasyPoiUtils.importExcel(file, 1, 1, OrderIdVo.class);
            if (list != null && list.size() > 0) {
                for (OrderIdVo orderIdVo : list
                ) {
                    OrderIdVo orderIdVo_one = new OrderIdVo();
                    log.info("orderId{}", orderIdVo.getOrderId());
                    if (orderIdVo != null && orderIdVo.getOrderId() != null && orderIdVo.getOrderId() != 0) {
                        ServerResponse responseImpl = violationsToSet(orderIdVo.getOrderId(), authentication);
                        if (responseImpl.getStatus() == 200) {
                            orderIdVo_one.setOrderId(orderIdVo.getOrderId());
                            orderIdVo_one.setDescribe("成功");
                            log.info("设置违规订单成功orderId{}", orderIdVo.getOrderId());
                        } else if ((responseImpl.getStatus() == 701)) {
                            orderIdVo_one.setOrderId(orderIdVo.getOrderId());
                            orderIdVo_one.setDescribe("查询不到此订单");
                            log.error("设置违规订单失败orderId{}", orderIdVo.getOrderId());
                        } else if ((responseImpl.getStatus() == 702)) {
                            orderIdVo_one.setOrderId(orderIdVo.getOrderId());
                            orderIdVo_one.setDescribe("该订单已是违规订单");
                            log.error("设置违规订单失败orderId{}", orderIdVo.getOrderId());
                        }
                    }
                    listResult.add(orderIdVo_one);
                }
                //  EasyPoiUtils.exportExcel(listResult, "处理结果", "违规订单", OrderIdVo.class, EasyPoiStyleUtils.class, "违规订单处理结果.xls", response);

                return listResult;
            } else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("设置违规订单异常{}", e.getMessage());
        }
        return null;
    }

    @Override
    public List<MaintainOrderVo> maintainOrderList(HttpServletResponse response, MultipartFile file, UserVO authentication) {
        List<MaintainOrderVo> listResult = new ArrayList<>();
        try {
            List<MaintainOrderVo> list = EasyPoiUtils.importExcel(file, 1, 1, MaintainOrderVo.class);
            if (list != null && list.size() > 0) {
                for (MaintainOrderVo maintainOrderVo : list) {
                    //log.info("订单Id:{},维权金额:{},返还金额:{}",maintainOrderVo.getOrderId(),maintainOrderVo.getMaintainMoney(),maintainOrderVo.getReturnMoney());
                    // 获取错误列表
                    MaintainOrderVo MaintainOrder = new MaintainOrderVo();
                    log.info("orderId{}", maintainOrderVo.getOrderId());

                    if (maintainOrderVo != null && maintainOrderVo.getOrderId() != null && maintainOrderVo.getOrderId() != 0) {
                        //ServerResponse responseImpl = miantainOrderDeal(maintainOrderVo, authentication);
                        ServerResponse responseImpl = handlerMiantainOrderDeal(maintainOrderVo);
                        if (responseImpl.getStatus() == 200) {
                            MaintainOrder.setOrderId(maintainOrderVo.getOrderId());
                            MaintainOrder.setDescribe("成功");
                            log.info("维权订单设置成功orderId{}", maintainOrderVo.getOrderId());
                        } else {
                            MaintainOrder.setOrderId(maintainOrderVo.getOrderId());
                            MaintainOrder.setDescribe(responseImpl.getMsg());
                            log.error("维权订单设置失败orderId{},失败的信息:{}", maintainOrderVo.getOrderId(), responseImpl.getMsg());
                        }
                    }
                    listResult.add(MaintainOrder);
                }

                //记录操作人日志
                SysLog sysLog = new SysLog();
                sysLog.setUserId(authentication.getUserId());
                sysLog.setMethodExplain("批量上传Excel设置维权订单，日期：" + DateUtils.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss"));
                sysLog.setUserType(2);
                sysLog.setRequestUrl("web/order/violations/import");
                sysLog.setLogType(1);
                sysLogCommon.save(sysLog);

                return listResult;
            } else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("设置违规订单异常{}", e.getMessage());
        }
        return null;
    }

    /**
     * 处理维权订单 （zhuchao）
     *
     * @param
     * @return
     */
    public ServerResponse handlerMiantainOrderDeal(MaintainOrderVo maintainOrderVo) {
        //校验excel的值
        if (StringUtils.isEmpty(maintainOrderVo.getOrderId()) || StringUtils.isEmpty(maintainOrderVo.getMaintainMoney()) || StringUtils.isEmpty(maintainOrderVo.getReturnMoney())) {
            return ServerResponse.createByErrorCodeMessage(700, "Excel上传内容，不允许为空");
        }
        List<AppUserOrder> list = appUserOrderMapper.selectAppUserOrderListByTradeId(maintainOrderVo.getOrderId());
        AppOrderDetail appOrderDetail = appOrderDetailMapper.selectAppOrderDetailByTradeId(maintainOrderVo.getOrderId());
        if (!CollectionUtils.isEmpty(list) && appOrderDetail != null) {
            for (AppUserOrder appUserOrder : list) {
                if (appUserOrder.getOrderStatus() == 13) {
                    return ServerResponse.createByErrorCodeMessage(702, "设置失败,已经是失效订单");
                }
                if (appUserOrder.getOrderSettleStatus() == 3 || appUserOrder.getCommissionOld() != null) {
                    return ServerResponse.createByErrorCodeMessage(703, "设置失败,已经是维权订单");
                }
                //特殊参数校验
                if (appUserOrder.getCommission() == null || appUserOrder.getOrderSettleStatus() == null) {
                    return ServerResponse.createByErrorCodeMessage(704, "设置失败,订单属性异常");
                }
                //计算扣除金额
                Map<String, Double> doubleMap = handleSubtractCommission(maintainOrderVo, appUserOrder, appOrderDetail);
                if (doubleMap == null) {
                    return ServerResponse.createByErrorCodeMessage(705, "设置失败,返还金额超过联盟返佣");
                }
                //扣除补贴逻辑
                Boolean aBoolean = handleUserCommission(appUserOrder, appOrderDetail, doubleMap);
                if (!aBoolean) {
                    return ServerResponse.createByErrorCodeMessage(706, "设置失败,处理分佣异常");
                }
            }
            return ServerResponse.createBySuccessMessage("设置成功");
        }

        return ServerResponse.createByErrorCodeMessage(701, "订单不存在");
    }

    /**
     * 计算应扣除金额
     *
     * @param maintainOrderVo excel上传的维权数据
     * @param appUserOrder    用户order数据
     * @return
     */
    public Map<String, Double> handleSubtractCommission(MaintainOrderVo maintainOrderVo, AppUserOrder appUserOrder, AppOrderDetail appOrderDetail) {
        //维权金额
        double maintainMoney = maintainOrderVo.getMaintainMoney().doubleValue();
        //返还金额
        double returnMoney = maintainOrderVo.getReturnMoney().doubleValue();
        //用户佣金
        double commission = appUserOrder.getCommission().doubleValue();
        //联盟佣金
        double pubSharePreFee = Double.valueOf(appOrderDetail.getPubSharePreFee());

        //校验上传的返回金额是否合法
        double div = ComputeUtil.div(returnMoney, pubSharePreFee);
        if (ComputeUtil.compare(div, 1) > 0) {
            return null;
        }

        //==================order表应扣佣金计算=====================
        log.info("维权金额:{},返还金额:{},用户佣金:{},联盟佣金:{}", maintainMoney, returnMoney, commission, pubSharePreFee);
        //计算公式（应扣补贴（X） =  (返还金额 * 用户补贴金额 )/联盟佣金 ）
        double pub = ComputeUtil.mul(returnMoney, commission);
        double divCom = ComputeUtil.div(pub, pubSharePreFee, 2);
        log.info("订单：{},对应的人id：{},应扣除的补贴金额：{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), divCom);

        //==================detail表应扣联盟返佣=====================
        //计算公式（应扣联盟佣金（X） = 返还金额）
        log.info("订单：{},对应的人id：{},应扣除的联盟金额：{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), returnMoney);
        Map<String, Double> map = new HashMap<>();
        map.put("subCom", divCom);
        map.put("subPub", returnMoney);
        return map;
    }

    /**
     * 扣除账户补贴金额
     *
     * @param appUserOrder   订单
     * @param appOrderDetail 订单详情
     * @param map            应扣除的补贴佣金，联盟佣金
     * @return
     */
    public Boolean handleUserCommission(AppUserOrder appUserOrder, AppOrderDetail appOrderDetail, Map<String, Double> map) {

        try {
            //入账中（order_settle_status=1）：付款，未结算，未失效  【处理order表，user表】
            //已到账（order_settle_status=2）：结算 【处理order表，user表】
            //半维权不考虑红包
            double subCom = map.get("subCom").doubleValue();
            double subPub = map.get("subPub").doubleValue();
            //==================detail表处理逻辑==========================
            //联盟佣金
            String pubSharePreFeeOld = appOrderDetail.getPubSharePreFee();
            double pubSharePreFee = Double.valueOf(pubSharePreFeeOld);
            //（联盟佣金 - 应该扣除联盟佣金） = 维权后联盟佣金
            double sub2 = ComputeUtil.sub(pubSharePreFee, subPub);
            log.info("用户id:{},订单号:{},维权后金额：{}", appUserOrder.getUserId(), appOrderDetail.getTradeId(), sub2);
            AppOrderDetail orderDetail = new AppOrderDetail();
            orderDetail.setOrderDetailid(appOrderDetail.getOrderDetailid());
            DecimalFormat dFormat = new DecimalFormat("0.00");
            orderDetail.setPubSharePreFee(dFormat.format(sub2));
            appOrderDetailService.updateById(orderDetail);
            //==================order表处理逻辑============================
            //用户佣金
            double commission = appUserOrder.getCommission().doubleValue();
            //(用户佣金 - 应该扣除的金额) = 维权后用户佣金
            double sub = ComputeUtil.sub(commission, subCom);
            log.info("用户id:{},订单号:{},维权后金额：{}", appUserOrder.getUserId(), appUserOrder.getOrderId(), sub);
            AppUserOrder userOrder = new AppUserOrder();
            userOrder.setTableId(appUserOrder.getTableId());
            userOrder.setCommission(new BigDecimal(sub));
            userOrder.setCommissionOld(new BigDecimal(commission));
            userOrder.setPubSharePreFeeOld(new BigDecimal(pubSharePreFeeOld));
            Integer orderSettleStatus = appUserOrder.getOrderSettleStatus();
            //维权订单标记(全:2;半:1)
            if (ComputeUtil.compare(sub, 0) == 0) {
                userOrder.setMaintainType(2);
            }else {
                userOrder.setMaintainType(1);
            }
            appUserOrderService.updateById(userOrder);

            //==================app_user_red_reward表处理逻辑=================
            //红包金额
            double redMoney = handleUserRedReward(appUserOrder, sub);
            log.info("用户id:{},红包金额：{}", appUserOrder.getUserId(), redMoney);

            //==================app_user表处理逻辑============================
            //账户变更
            double newBalance = redMoney;
            if (orderSettleStatus == 2) {
                newBalance = ComputeUtil.add(subCom, redMoney);
            }
            log.info("用户id:{},账户应扣金额：{}", appUserOrder.getUserId(), newBalance);
            if (ComputeUtil.compare(newBalance, 0) > 0) {
                AppUser appUser = appUserService.selectAppUserByUserId(appUserOrder.getUserId());
                double balance = appUser.getBalance().doubleValue();
                //账户变更后金额
                double sub1 = ComputeUtil.sub(balance, newBalance);
                AppUser user = new AppUser();
                user.setTableId(appUser.getTableId());
                user.setBalance(new BigDecimal(sub1));
                appUserService.updateById(user);

                //添加账户变更日志
                syUserMoneyLogService.addSyUserMoneyLog(appUser.getUserId(), new BigDecimal(balance), new BigDecimal(newBalance), "维权订单补贴扣除", null, 1);
                log.info("维权订单用户id:{},订单id:{},账户变更前余额：{}，账户应扣金额：{},账户变更后余额：{}", appUser.getUserId(), appUserOrder.getOrderId(), balance, newBalance, sub1);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 处理首购红包
     *
     * @param appUserOrder 订单
     * @param sub          维权后佣金
     * @return
     */
    public double handleUserRedReward(AppUserOrder appUserOrder, double sub) {
        double balance = 0.00;
        //只处理全维权
        if (ComputeUtil.compare(sub, 0) == 0) {
            //是否存在首购红包(已领取需要扣除，其它状态就设置无效)
            AppUserRedReward appUserRedReward = appUserRedRewardService.selectAppUserRedRewardById(appUserOrder.getOrderId(), appUserOrder.getUserId());
            if (appUserRedReward != null) {
                if (appUserRedReward.getHbStatus() == 5) {
                    //返回已经领取的红包金额
                    balance = appUserRedReward.getHbMoney().doubleValue();
                }

                //处理红包为失效
                AppUserRedReward reward = new AppUserRedReward();
                reward.setTableId(appUserRedReward.getTableId());
                reward.setHbStatus(4);
                appUserRedRewardService.updateById(reward);
            }
        }

        return balance;
    }

    /**
     * 处理维权订单
     *
     * @param
     * @return
     */
    public ServerResponse miantainOrderDeal(MaintainOrderVo maintainOrderVo, UserVO authentication) {
        List<AppUserOrder> list = appUserOrderMapper.selectAppUserOrderListByTradeId(maintainOrderVo.getOrderId());
        AppOrderDetail appOrderDetail = appOrderDetailMapper.selectAppOrderDetailByTradeId(maintainOrderVo.getOrderId());
        Administrator administrator = administratorService.getById(authentication.getUserId());
        if (list != null && list.size() > 0) {
            for (AppUserOrder appUserOrder : list) {
                SysLog sysLog = new SysLog();
                sysLog.setUserId(authentication.getUserId());
                sysLog.setMethodExplain(administrator.getAdminitratorName() + "把订单号为" + appUserOrder.getOrderId() + "设置成维权订单");
                if (appUserOrder != null && appUserOrder.getOrderStatus() == 3) {
                    sysLog.setResponseParams("设置失败,已经是失效订单");
                    return ServerResponse.createByErrorCodeMessage(702, "设置失败,已经是失效订单");
                }
                if (appUserOrder != null) {
                    AppUserOrder order = new AppUserOrder();
                    BigDecimal returnMoney = maintainOrderVo.getReturnMoney();


                    order.setTableId(appUserOrder.getTableId());
                    order.setOrderStatus(13);//设置为失效
                    order.setOrderSettleStatus(3);//违规订单
                    int i = appUserOrderMapper.updateAppUserOrder(order);

                    if (i > 0) {
                        sysLog.setResponseParams("未结算订单，违规订单设置成功");
                        log.info("未结算订单，违规订单设置成功，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                    } else {
                        sysLog.setResponseParams("未结算违规订单修改状态失败");
                        log.error("未结算违规订单修改状态失败，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                    }
                    AppUserRedReward appUserRedReward = iAppUserRedRewardService.selectAppUserRedRewardById(appUserOrder.getOrderId(), appUserOrder.getUserId());
                    if (appUserRedReward != null && appUserRedReward.getHbStatus() != 5) {
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);
                        if (appUserRedReward.getHbType() == 3) {
                            log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            updateUserCommon.UpdateUserTaskStatus(appUserOrder.getUserId(), 6);
                        }
                    }

                } else if (appUserOrder != null && appUserOrder.getOrderSettleStatus() == 2) {
                    AppUserOrder order = new AppUserOrder();
                    order.setTableId(appUserOrder.getTableId());
                    order.setOrderStatus(13);//设置为失效
                    order.setOrderSettleStatus(3);//违规订单
                    int i = appUserOrderMapper.updateAppUserOrder(order);
                    if (i > 0) {
                        sysLog.setResponseParams("结算订单，违规订单设置成功");
                        log.info("结算订单，违规订单设置成功，orderId{}userId{}分佣{}", appUserOrder.getOrderId(), appUserOrder.getUserId(), appUserOrder.getCommission());
                        AppUser appUser = appUserMapper.selectAppUserByUserId(appUserOrder.getUserId());
                        BigDecimal balance = appUser.getBalance();
                        AppUser appUser1 = new AppUser();
                        appUser1.setTableId(appUser.getTableId());
                        appUser1.setUserId(appUser.getUserId());
                        appUser1.setBalance(balance.subtract(appUserOrder.getCommission()));
                        int ii = appUserMapper.updateAppUser(appUser1);
                        log.info("分佣扣除成功，userId{}用户余额{}", appUserOrder.getUserId(), balance.subtract(appUserOrder.getCommission()).toString());

                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(appUserOrder.getUserId(), balance, BigDecimalUtils.Format(appUserOrder.getCommission()), "违规订单分佣扣除", 2, 1);

                    } else {
                        log.info("分佣扣除失败，userId{}", appUserOrder.getUserId());

                    }

                    AppUserRedReward appUserRedReward = iAppUserRedRewardService.selectAppUserRedRewardById(appUserOrder.getOrderId(), appUserOrder.getUserId());

                    if (appUserRedReward != null && appUserRedReward.getHbStatus() == 5) {
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);

                        if (appUserRedReward.getHbType() == 3) {
                            if (j) {
                                log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            } else {
                                log.error("首购红包设置失效失败，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            }
                            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(2);
                            SyUserTask syUserTask = new SyUserTask();
                            syUserTask.setUserId(appUserRedReward.getUserId());
                            syUserTask.setTaskTypeId(2);
                            syUserTask.setTaskType(syTaskType.getTaskType());
                            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
                            syUserTask.setTaskStatus(5);
                            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
                            syUserTask.setTaskRewardMoney(BigDecimal.valueOf(0).subtract(syTaskType.getTaskRewardMoney()));
                            syUserTask.setTaskRewardDate(new Date());
                            syUserTask.setEnable(1);
                            iSyUserTaskService.insertsyUserTask(syUserTask);
                        } else if (appUserRedReward.getHbType() == 2) {
                            if (j) {
                                log.info("邀请红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            } else {
                                log.error("邀请红包设置失效失败");
                            }
                            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(5);
                            SyUserTask syUserTask = new SyUserTask();
                            syUserTask.setUserId(appUserRedReward.getUserId());
                            syUserTask.setTaskTypeId(5);
                            syUserTask.setTaskType(syTaskType.getTaskType());
                            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
                            syUserTask.setTaskStatus(5);
                            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
                            syUserTask.setTaskRewardMoney(BigDecimal.valueOf(0).subtract(syTaskType.getTaskRewardMoney()));
                            syUserTask.setTaskRewardDate(new Date());
                            syUserTask.setEnable(1);
                            iSyUserTaskService.insertsyUserTask(syUserTask);
                        }

                        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(appUserOrder.getUserId());
                        if (syUserMoney != null) {
                            SyUserMoney syUserMoney1 = new SyUserMoney();
                            syUserMoney1.setTableId(syUserMoney.getTableId());
                            syUserMoney1.setCashBalanceAmount(syUserMoney.getCashBalanceAmount().subtract(appUserRedReward.getHbMoney()));
                            syUserMoney1.setCashTotalAmount(syUserMoney.getCashTotalAmount().subtract(appUserRedReward.getHbMoney()));
                            int jj = iSyUserMoneyService.updateSyUserMoney(syUserMoney1);
                            if (jj > 0) {
                                log.info("微信余额扣除红包奖励成功，userId{}金额{}余额{}", syUserMoney.getUserId(), appUserRedReward.getHbMoney(), syUserMoney.getCashBalanceAmount().subtract(appUserRedReward.getHbMoney()));
                            } else {
                                log.error("红包奖励扣除失败，userId{}金额{}", syUserMoney.getUserId(), appUserRedReward.getHbMoney());
                            }
                        }
                    } else if (appUserRedReward != null && (appUserRedReward.getHbStatus() == 2 || appUserRedReward.getHbStatus() == 3)) {
                        //红包未到账时,设置红包失效
                        AppUserRedReward appUserRedReward1 = new AppUserRedReward();
                        appUserRedReward1.setTableId(appUserRedReward.getTableId());
                        appUserRedReward1.setHbStatus(4);
                        Boolean j = iAppUserRedRewardService.updateById(appUserRedReward1);

                        if (appUserRedReward.getHbType() == 3) {
                            log.info("首购红包设置为失效，userId{}金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            updateUserCommon.UpdateUserTaskStatus(appUserOrder.getUserId(), 6);
                        }
                    }

                }
                sysLogCommon.save(sysLog);
            }
            return ServerResponse.createBySuccessMessage("设置成功");
        }
        return ServerResponse.createByErrorCodeMessage(701, "订单不存在");
    }

    @Override
    public ServerResponse<PageInfo> selectAppOrderDetailListNew(int currentPage, int pageSize, Long userId) {
        PageHelper.startPage(currentPage, pageSize);
        List<AppOrderDetailVo> list = appOrderDetailMapper.selectAppOrderDetailListNew(userId);
        return ServerResponse.createBySuccess("查找成功", new PageInfo(list));
    }

    @Override
    public int deleteOrderDetail(Long orderId) {
        return appOrderDetailMapper.deleteOrderDetail(orderId);
    }

    @Override
    public boolean handleDetailStatus() {
        //查询所有需要处理的订单，及订单详情
        QueryWrapper<AppOrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_status", 14);
        List<AppOrderDetail> list = iAppOrderDetailService.list(queryWrapper);
        for (AppOrderDetail detail : list) {

            //AppOrderDetail detail = appOrderDetailService.selectAppOrderDetailByTradeId(Long.valueOf("587440590146227709"));
            //更新detail
            detail.setPayStatus("3");
            detail.setEarningTime(new Date().getTime());
            iAppOrderDetailService.updateById(detail);
            //更新Order
            AppUserOrder appUserOrder = appUserOrderMapper.selectAppUserOrderByTradeIdNew(detail.getTradeId());
            if (appUserOrder == null) {
                continue;
            }
            //关联用户
            AppUser appUser = appUserService.selectAppUserByUserId(appUserOrder.getUserId());
            if (appUser == null) {
                continue;
            }
            //处理红包和任务
            handleRedOrTask(appUserOrder);

            if (detail.getGoodFrees() != null && detail.getGoodFrees() == 1) {
                //处理免单商品结算
                try {
                    handleFreeGoods(appUserOrder, detail, appUser);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                //处理非免单商品
                try {
                    handleNotFreeGoods(appUserOrder, detail, appUser);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }

        return true;
    }


    /**
     * 处理红包和任务
     *
     * @param userOrder
     */
    public void handleRedOrTask(AppUserOrder userOrder) {
        //判断开关是否打开
        if (userOrder.getOrderGrade() == 1) {
            AppUserRewardSetup rewardSetup = null;
            if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
            } else {
                rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
                redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
            }
            //邀请赚钱红包（上级）
            AppUserRedReward appUserRedReward = new AppUserRedReward();
            long expireTime = DateFormatUtils.addDate(new Date(), 0).getTime();
            appUserRedReward.setExpireTime(expireTime);
            appUserRedReward.setOrderId(userOrder.getOrderId());
            appUserRedReward.setHbType(2);
            appUserRedReward.setHbStatus(2);
            int redMoneyInvi = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

            //首购红包（本级）
            AppUserRedReward appUserRedReward2 = new AppUserRedReward();
            long expireTime2 = DateFormatUtils.addDate(new Date(), 0).getTime();
            appUserRedReward2.setExpireTime(expireTime2);
            appUserRedReward2.setOrderId(userOrder.getOrderId());
            appUserRedReward2.setHbType(3);
            appUserRedReward2.setHbStatus(2);
            int redMoneyTask = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);

            //增加或修改任务日志状态
            AppUserRedReward userRedReward = appUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
            if (userRedReward != null) {
                log.info("订单结算---更新日志状态红包userI{}", userRedReward.getUserId());
                updateUserCommon.UpdateUserTaskStatus(userRedReward.getUserId(), 4);
            }
            log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
        }
    }

    /**
     * 结算免单商品
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws Exception {
        //更新总返佣金
        iGoodsFreeService.updateTotalRetureAmountByGoodsId(userOrder.getTableId());

        //免单商品佣金延迟10天到账
        AppUserOrder userOrder4 = new AppUserOrder();//构建佣金延迟
        userOrder4.setLargeAmountYes(1);
        userOrder4.setLargeAmountTime(getDateTime(0));//延迟天数毫秒
        userOrder4.setTableId(userOrder.getTableId());
        userOrder4.setOrderSettleStatus(1);
        userOrder4.setOrderStatus(3);
        userOrder4.setFreezeDay(0);
        int i3 = appUserOrderService.updateAppUserOrder(userOrder4);
        log.info("结算订单(免单延迟)结果", i3);
        if (i3 > 0 && isSendMsg(7)) {
            iAppNewsLogService.newsType(userOrder.getUserId(),
                    NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
        }

        //结算成功公众号提醒
        log.info("app_order_detail的trade_id:{}", appOrderDetail.getTradeId());
        BigDecimal commission = userOrder.getCommission();
        String commissionStr = "0";
        if (commission != null) {
            commissionStr = userOrder.getCommission().toString();
        }
        commissionStr += "元";
        String tkEarningTime = appOrderDetail.getTkEarningTime();
        if (tkEarningTime == null) {
            tkEarningTime = "暂无";
        }
        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());
        log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));

    }

    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Integer start) {

        return org.apache.commons.lang3.time.DateUtils.addDays(new Date(), start).getTime();
    }

    /**
     * 通过开关判断是否要发消息
     *
     * @return
     * @id 开关类型
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息", id);
            return true;
        }
        log.info("消息类型{} 消息关", id);
        return false;
    }

    /**
     * 处理非免单商品结算
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleNotFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws IOException {
        //查询佣金是否符合佣金冻结设置
        CommissionFreeze freeze = null;
        if (redisTemplateService.hasKey("CommissionFreezeStuep")) {
            freeze = redisTemplateService.getTByKey("CommissionFreezeStuep", CommissionFreeze.class);
        } else {
            freeze = commissionFreezeService.selectByPrimaryKeyLIMIT(1);
            redisTemplateService.set("CommissionFreezeStuep", freeze, 60 * 60);
        }

        //相等返回0，大于返回1，小于返回-1
        AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟
        BigDecimal userCommission = userOrder.getCommission();
        if (BigDecimalUtils.Format(userCommission).compareTo(BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
            userOrder2.setLargeAmountYes(1);
            userOrder2.setLargeAmountTime(getDateTime(0));//延迟天数毫秒
            userOrder2.setTableId(userOrder.getTableId());
            userOrder2.setOrderSettleStatus(1);
            userOrder2.setOrderStatus(3);
            userOrder2.setFreezeDay(0);
            int i3 = appUserOrderService.updateAppUserOrder(userOrder2);
            log.info("结算订单(普通商品延迟){}", i3);
            if (i3 > 0 && isSendMsg(7)) {
                iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
            }
        } else {
            BigDecimal beforeBalance = appUser.getBalance();
            //根据订单id查询订单
            switch (userOrder.getOrderGrade()) {
                case 1:
                    int i3 = appUserService.updateAppUseraddbalance(userOrder.getUserId(), BigDecimalUtils.Format(userOrder.getCommission()));
                    log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                    log.info("普通商品补贴到账开始发送消息{}", i3);
                    if (i3 > 0) {
                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(), beforeBalance, BigDecimalUtils.Format(userOrder.getCommission()), "普通商品补贴到账", 2, 0);
                        if (isSendMsg(7)) {
                            iAppNewsLogService.newsType(userOrder.getUserId(), NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                        }
                        //结算成功公众号提醒
                        log.info("app_order_detail的trade_id:{}", appOrderDetail.getTradeId());
                        BigDecimal commission = userOrder.getCommission();
                        String commissionStr = "0";
                        if (commission != null) {
                            commissionStr = userOrder.getCommission().toString();
                        }
                        commissionStr += "元";
                        String tkEarningTime = appOrderDetail.getTkEarningTime();
                        if (tkEarningTime == null) {
                            tkEarningTime = "暂无";
                        }
                        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());
                        log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));
                    }
                    break;

                default:
                    break;
            }
            AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
            userOrder3.setOrderStatus(3);
            userOrder3.setOrderSettleStatus(2);
            userOrder3.setTableId(userOrder.getTableId());
            int i4 = appUserOrderService.updateAppUserOrder(userOrder3);
            log.info("结算订单（普通商品不延迟）已经将钱转到账i4{}", i4);
        }
    }

}
